// 引入接口文件
import {
  getDetail,
  update,
  create,
  labelQueryList,
  areAddressGet,
  houseListGet,
  gethouseTypeList,
  queryAccount,
  queryInfo,
  regionArea,
  getProduct ,
  getAccountDetail,
  getPayCodeList
} from './productEditServ.js'

// 对象和JSON字符串互转
import { parse } from 'qs'
// 弹出消息框
import { message } from 'antd'
// 日期处理对象
/*isEmpty 对象是否为空
 *isArray 对象是否数组
 *cloneDeep 对象深拷贝
 */
import { isEmpty, isArray, cloneDeep, merge, pick } from 'lodash'
import moment from 'moment/moment'
// 引入路由对象
import { hashHistory } from 'dva/router'
import AppBus from '../../../../utils/bus'
import { makeAddress ,download} from "utils/util"
let productTypeLabelMap = { 1: '详细房号', 2: '车位位置', 3: '商铺位置',4:'商品名称',5:'商品名称',6:'商品名称',7:'商品名称'}
// 初始默认状态
const defultState = {
  xxx: '1',
  loading: false,
  btnLoading: false,
  id: '',
  parentProductId: '',
  pageType: 'detail',
  sellType: '1',
  isClone: false,
  checked: false,
  accountList: [],//根据项目查找对公账户
  allAddress: [],
  houseList: [],
  detailInfo: {},
  standards:{
    volume:'',
    weight:'',
    power:'',
    size:'',
    color:'',
    producingArea:'',
    other:''
  },
  show:false,
  formData: {
    'projectId': '',
    'projectName': '',
    'houseTypeName': ['','',''],
    'detail': '',
    'area': '',
    'productType': '',
    'propertyType': '',
    'seckillPrice': '',
    'originalPrice': '',
    'securityMoney': '',
    'earnestMoney': '',
    'squarePrice': '',
    'orientation': '',
    'imageUrls': [],
    'tags': [],
    'productLabel': '详细房号：',
    'city': '',
    'province': '',
    'productId': '',
    'productBankAccountId': '',
    'enrollType':'',
    'promotionDetail':'',//商品描述
    'productDesc':'',//商品介绍
    "color": "",
    "other": "",
    "power": "",
    "producingArea": "",
    "size": "",
    "volume": "",
    "weight": "",
    "bankAccount":'',//银行卡账号
   " startTime":'',
   "needEnroll":'',//是否需要报名费
   'showStockFlag':1//是否显示库存 1是0否
  },
  accountType:1,
  selectOption: {
    value: '', // 选择的默认1
    des: '', // 选择的默认
  },
  medias:[],
  teamsOptions:[
    {value:'volume', label:'容量'},
    {value:'weight', label:'重量'},
    {value:'power', label:'功率'},
    {value:'size', label:'体积'},
    {value:'color', label:'颜色'},
    {value:'producingArea', label:'产地'},
    {value:'other', label:'其他'},
  ],
  // freeSecurityMoney:false,
  tagInputValue: '',
  tagInputVisible: false,
  imageUrls: [],
  tagsList: [],//所有标签
  houseTypeList: [],//户型列表
  tags: [],//已选中标签
  modalObj: {
    project: {
    visible: false,
    },
    productList: {
      visible: false,
    },
    productList1: {
      visible: false,
    },
    accountList:{
      visible: false,
    }
  },
  biz:{
    queryForm:{
      province: null,
      city:null,
      pageSize: 10,
      pageNo:1,
      name:null
    },
    selectedRowKeys:[]
  },
  biz1:{
    queryForm:{
      pageSize: 10,
      pageNo:1,
      regionId:'',
      provinceCode:'',
      cityCode:'',
      productBankAccountId:''
    },
    selectedRowKeys:[],
    selectedRows:[]
  },
  area1:[],
  products:[],
  areaList:[],
  payCodeList:[],//商户支付号列表
  isAll:false//列表是否可选择全部
}

// 声明module
const tmpModule = {
  // namespace: 'secondKillingSetting',
  // 默认状态
  state: cloneDeep(defultState),
  // 入口函数(先执行)
  subscriptions: {
    setup({ dispatch, history }) {
      history.listen(({ pathname, query }) => {
        // 页面路由匹配时执行
        if ('' + tmpModule.pathname === '' + pathname) {
          dispatch({ type: 'updateStore', payload: { ...cloneDeep(defultState), ...query } })//每次进去页面先重置状态
          dispatch({type:'getPayCodeList',payload:{}});
          console.log('subscriptions', pathname, query)
          if (query.pageType == 'edit') {
            if(query.detailType=='good'){
              dispatch({
                type: 'getDetail',
                payload: {
                  productId:query.id,
                }
              })
            }else{
              dispatch({
                type: 'queryInfo',
                payload: {
                  pageType: query.pageType,
                  id: query.id,
                  isClone: query.isClone||false,
                }
              })
            }
          } else {
            dispatch({
              type: 'updateStore',
              payload: {
                pageType: query.pageType,
                id: query.id,
                isClone: query.isClone||false,
              }
            })
          }
          dispatch({ type: 'gethouseTypeList', payload: {} })
          dispatch({ type: 'getArea', payload: {} })
          dispatch({ type: 'getLabelQueryList', payload: {} })
          // dispatch({ type: 'queryAccount', payload: { id: query.id} })
          dispatch({ type: 'regionArea', payload: {} })
          
        } // end if
      }) // end listen
    },
  },

  // 方法列表
  effects: {
    *getPayCodeList({payload},{put,call,select}){
      try{
        const { rows, success } = yield call(getPayCodeList,{});
        console.log(rows);
        if(success){
          if(rows){
            rows.map((item,i)=>{
              item.key = i
            })
            console.log('rows:',rows)
            yield put({ type: 'updateStore', payload: { payCodeList: rows } });
          }
        }
      }catch(e){

      }
    },
    *regionArea({payload},{put,call,select}){
			let {areaList,biz1 }=yield select(state => state[tmpModule.namespace])
					const {success,data}=yield call(regionArea)
					if(success){
						if(biz1.queryForm.regionId){
							data.map((item,index)=>{
                console.log(item)
								if(item.value==biz1.queryForm.regionId){
									areaList = makeAddress(item.children,2)
								}
							})
						}
						yield put({type:'updateStore',payload:{area1:data,areaList}})
						yield put({type:'getProduct',payload:{}})
					}
				},
		*getProduct({payload},{put,call,select}){
			let {products,biz1} = yield select(state => state[tmpModule.namespace])
			if(biz1.queryForm.cityCode){
				const { data, success } = yield call(getProduct,{cityCode:biz1.queryForm.cityCode});
				if(success){
					products=data
					yield put({ type: 'updateStore',payload:{products}})
				}
			}
			
		},
    //非房产类商品详情
    *getDetail({payload},{put,call,select}){
      debugger
      let { id, detailInfo, formData, tags, imageUrls,sellType,selectOption,teamsOptions,biz,isAll } = yield select(state => state[tmpModule.namespace])
      const { success, msg, data } = yield call(getDetail, payload)
      if (success) {
        for(let x in teamsOptions){
          for(let y in data){
            if(teamsOptions[x].value==y){
              selectOption.value=y
              selectOption.des=data[y]
            }
          }
        }
        detailInfo = data || {}
        formData = data || {}
        formData.projectId = formData.parentProductId || '0';
        tags = data.tags || []
        formData.detail=formData.name
        if(data.catalogId=='9004'){
          formData.productType='4'
        }else if(data.catalogId=='9005'){
          formData.productType='5'
        }else if(data.catalogId=='9006'){
          formData.productType='6'
        }else if(data.catalogId=='9009'){
          formData.productType='7'
        }
        isAll = Number(formData.productType)>3
        if(formData.medias){
         imageUrls = formData.medias.map(item => item.fileUrl)
        }
        formData.productDesc=formData.description
        formData.productLabel = productTypeLabelMap[formData.productType] || null
        biz.queryForm={
          ...biz.queryForm,
          province:data.province,
          city:data.city,
          name:data.parentProductName
        } 
        biz.selectedRowKeys[0]=data.parentProductId
        // yield put ({type: `houseListGet`, payload: {province: data.province, city:data.city,pageSize: 10000}})
        // yield put ({type: `queryAccount`, payload: {id:formData.projectId}})
        // const { success, rows } = yield call(houseListGet, { province: data.province, city: data.city, pageSize: 10000 });
        // if (success) {
        //   yield put({ type: 'updateStore', payload: { houseList: rows || [] } })
        // }
      }
      debugger
      yield put({
        type: 'updateStore',
        payload: {
          detailInfo,
          formData,
          tags,
          imageUrls,
          ...payload,
          biz,
          isAll
        }
      })
    },
    // 查询记录  详情
    * queryInfo({ payload }, { put, call, select }) {
      let { id, detailInfo, formData, tags, imageUrls,sellType,selectOption,teamsOptions ,accountList,biz ,biz1,isAll} = yield select(state => state[tmpModule.namespace])
      const { success, msg, data } = yield call(queryInfo, { id: payload.id || id, })
      let t1 = moment()
      if (success) {
        for(let x in teamsOptions){
          for(let y in data){
            if(teamsOptions[x].value==y){
              selectOption.value=y
              selectOption.des=data[y]
            }
          }
        }
        detailInfo = data || {}
        formData = data || {}
        formData.projectId = formData.projectId;
        tags = data.tags || []
        imageUrls = data.imageUrls || []
          formData.enrollType = data.enrollType
       if( formData.enrollType === 1 ){
           formData.securityMoney = ''
       }
        formData.productLabel = productTypeLabelMap[formData.productType] || null
        if(!formData.houseTypeName){
          formData.houseTypeName=['','','',''];//x室x厅x卫
        }else{
          formData.houseTypeName=(formData.houseTypeName||'').split(/[室|厅|厨|卫]/);//x室x厅x卫
          if(formData.houseTypeName>4){
            formData.houseTypeName.splice(2,1)//去掉厨房
          }
        }
        biz.queryForm={
          ...biz.queryForm,
          province:data.province,
          city:data.city,
          name:data.projectName
        } 
        biz.selectedRowKeys[0]=data.projectId
        biz1.queryForm={
          ...biz1.queryForm,
          productBankAccountId:data.productBankAccountId,
        }
        isAll = Number(formData.productType)>3
      }
      yield put({
        type: 'updateStore',
        payload: {
          detailInfo,
          formData,
          accountType:formData.productBankAccountId?2:1,
          tags,
          imageUrls,
          ...payload,
          show:moment(formData.startTime).isBefore(t1) && formData.status!=5,
          biz,
          biz1,
          isAll
        }
      })
      // yield put ({type: `queryAccount`, payload: {formData, id: formData.projectId,}})
      if(data.productBankAccountId){
        yield put({
          type:'getAccountDetail',
          payload:{
            id:data.productBankAccountId
          }
        })
      }
      
    },
    *getAccountDetail({payload},{put,call,select}){
      let {biz1,formData}=yield select(state => state[tmpModule.namespace])
      let {data,success}=yield call(getAccountDetail,payload)
      if(success){
        console.log(data)
        biz1.queryForm={
          ...biz1.queryForm,
          provinceCode:data.province,
          cityCode:data.city,
          regionId:data.regionId,
          productId:data.productId,
          province:data.province,
          city:data.city,
          accountName:data.accountName
        } 
        biz1.selectedRowKeys[0]=data.productBankAccountId
        biz1.selectedRows[0]=data
        formData={
          ...formData,
          bankAccount:data.bankAccount,
          accountName:data.accountName,
  
        }
        console.log(biz1)
        if(success){
          yield put({
            type:'updateStore',payload:{ biz1,formData}
          })
          yield put({ type: 'regionArea', payload: {} })
        }
      }
      
    },

    // 修改
    *update({ payload }, { put, select, call }) {
      let { id, formData, tags, imageUrls,selectOption,standards,accountType } = yield select(state => state[tmpModule.namespace])
      for(let i in standards){
        if(selectOption.value==i){
          standards[i]=selectOption.des
        }else{
          delete standards[i]
        }
      }
          // formData.volume = selectOption.des


          // formData.weight = selectOption.des


          // formData.power = selectOption.des


          // formData.size = selectOption.des


          // formData.color = selectOption.des


          // formData.producingArea = selectOption.des

          // formData.other = selectOption.des
          if(formData.productType<4){
            formData.stock=1
          }
          console.log(formData.stock,'formData.stock')
      let params = {
        seckillProductId: id,
        ...pick(formData, ['detail','waitPayTime', 'area', 'productType', 'propertyType', 'seckillPrice', 'originalPrice',
          'initPrice', 'grads', 'securityMoney', 'earnestMoney', 'squarePrice', 'orientation', 'imageUrls', 'tags', 'salePrice', 'consultantMobile', 'realtyConsultant', 'productId', 'projectId','productBankAccountId','enrollType','productDesc','promotionDetail','stock','bankAccount','needEnroll','payWay','merchantCode','showStockFlag'
        ]),
        imageUrls,
        ...standards,
      }
  
      // 商品类型非房源，不用传户型和户型朝向
      if(formData.productType==1){
        params.houseTypeName=formData.houseTypeName[0]+'室'+formData.houseTypeName[1]+'厅'+formData.houseTypeName[2]+'卫'
      }else{
        params.houseTypeName=''
        params.orientation=''
      }
      if(formData.productType>3){
        params.area = ''
        params.propertyType =''
      }
      accountType==1&&delete params.productBankAccountId
      const { success, msg, data } = yield call(update, { ...params })
      if (success) {
        message.success('操作成功', 1, () => {
          // yield put({type: 'queryInfo', payload: {}})
          let urlArray = MODULE_TO_ROUTES[tmpModule.namespace].urlArray
          console.log('urlArray', urlArray)
          AppBus.emit('closeTab', {
            key: urlArray[0],
            cbf: () => {
              hashHistory.push(urlArray[1])
              payload.resetFields()
            }
          })
        })
      }
    },
    // 新增
    *create({ payload }, { put, select, call }) {
      let { id, formData, tags, imageUrls,selectOption,standards,accountType} = yield select(state => state[tmpModule.namespace])
      // 转译成接口需要的
      yield put({ type: 'updateStore', payload: { btnLoading:true } })
      for(let i in standards){
        if(selectOption.value==i){
          standards[i]=selectOption.des
        }else{
          delete standards[i]
        }
      }
      // console.log(standards)
      // let key = ''
      // switch(selectOption.value+''){
      //   case '1':// 容量
      //     formData.volume = selectOption.des
      //     break;
      //   case '2':// 重量
      //     formData.weight = selectOption.des
      //     break;
      //   case '3':// 功率
      //     formData.power = selectOption.des
      //     break;
      //   case '4':// 体积
      //     formData.size = selectOption.des
      //     break;
      //   case '5':// 颜色
      //     formData.color = selectOption.des
      //     break;
      //   case '6':// 产地
      //     formData.producingArea = selectOption.des
      //     break;
      //   case '7':// 其他
      //     formData.other = selectOption.des
      // }
      // console.log('key')
      if(formData.productType<4){
        formData.stock=1
      }
      console.log(formData.stock,'formData.stock')
      let params = {
        ...pick(formData, ['projectId','waitPayTime', 'houseTypeName', 'detail', 'area', 'productType', 'propertyType', 'seckillPrice', 'originalPrice', 'securityMoney', 'earnestMoney', 'squarePrice', 'orientation', 'imageUrls', 'tags', 'salePrice', 'consultantMobile', 'realtyConsultant', 'productId','productBankAccountId','enrollType','productDesc','promotionDetail','stock','bankAccount','needEnroll','payWay','merchantCode','showStockFlag'
        ]),
        ...standards,
        imageUrls,
      }
      // 商品类型非房源，不用传户型和户型朝向
      if(formData.productType==1){
        params.houseTypeName=formData.houseTypeName[0]+'室'+formData.houseTypeName[1]+'厅'+formData.houseTypeName[2]+'卫'
      }else{
        params.houseTypeName=''
        params.orientation=''
      }
      accountType==1&&delete params.productBankAccountId
      const { success, msg, data } = yield call(create, { ...params })
      if (success) {
        message.success('操作成功', 1, () => {
          // yield put({type: 'queryInfo', payload: {}})
          let urlArray = MODULE_TO_ROUTES[tmpModule.namespace].urlArray
          console.log('urlArray', urlArray)
          AppBus.emit('closeTab', {
            key: urlArray[0],
            cbf: () => {
              hashHistory.push(urlArray[1])
              payload.resetFields()
            }
          })
        })
      }else{
        yield put({ type: 'updateStore', payload: { btnLoading:false } })
      }
    
  },

    // 获取区域地址
    *getArea({ payload }, { put, call, select }) {
      try {
        const { success, data } = yield call(areAddressGet)
        if (success) {
          //todo: 接口格式调整后删除
          let arr = [data[0]]
          data[0] = {
            label: '北京',
            value: '110100',
            children: arr
          }
          //去掉第三级，
          for (var i = 0; i < 33; i++) {
            for (var j = 0; j < data[i].children.length; j++) {
              delete data[i].children[j].children
            }
          }
          yield put({ type: 'updateStore', payload: { allAddress: data } })
        }
      } catch (e) {
        console.log(e)
      }
    },
    // 获取户型项目
    *houseListGet({ payload }, { put, call, select }) {
      try {
        const { success, rows } = yield call(houseListGet, { ...payload, pageSize: 10000 })
        if (success) {
          let list=rows||[]
          let arr=[]
          list.map((item,index)=>{
            arr.push({ label: item.name||'', value: item.productId+''||'' })
          })
          yield put({ type: 'updateStore', payload: { houseList: arr || [] } })
        }
      } catch (e) {
        console.log(e)
      }
    },
    // 标签列表
    * getLabelQueryList({ payload }, { put, call, select }) {
      try {
        const { rows } = yield call(labelQueryList, {type:4})
        yield put({ type: 'updateStore', payload: { tagsList: rows } })
      } catch (e) {
        console.log(e)
      }
    },
    // 对公账户
    * queryAccount({ payload }, { put, call, select }) {
      let { formData,id }=payload
      // let { formData }=yield select(state => state[tmpModule.namespace])
      try {
        const {success, msg, data=[], } = yield call(queryAccount, id)
        if(success){
          if(formData && formData.productBankAccountId){
              data.map((item,index)=>{
              if(formData.productBankAccountId===item.productBankAccountId){
                formData.bankAccount=data[index].bankAccount      
               }
            })
            }
        }
        console.log(formData)
        yield put({ type: 'updateStore', payload: { accountList: data,} })
      } catch (e) {
        console.log(e)
      }
    },

    *gethouseTypeList({ payload }, { put, call, select }) {
      try {
        let params = {
          pageNo: 1,
          pageSize: 1000,
          ...payload
        }
        const { success, msg, rows } = yield call(gethouseTypeList, { ...params })
        let list = []
        yield put({ type: 'updateStore', payload: { houseTypeList: rows || [] } })

      } catch (e) {
      }
    },

    //商品介绍图文编辑
    * dealEditor({ payload }, { put, select }) {
      let { detail } = yield select(state => state[tmpModule.namespace])
      let newDetail=Object.assign({}, detail)
      newDetail.detail=payload.detail
      yield put({ type: 'updateStore', payload: { detail: newDetail } });
    },
  },
  // 存入状态机
  reducers: {
    updateStore(preState, action) {
      return Object.assign({}, preState, action.payload);
    },
  }
}

export default tmpModule
